from typing import Any

from pydantic import BaseModel, Field, model_validator, ConfigDict

from app.utils.decorators.optional import optional
from ..models.base import SQLBaseModel, IdType
from ..models.role import BaseRole
from ..utils.model_converter import ModelConverter


class RoleCreate(BaseRole):
    pass


@optional(without_fields=["id"])
class RoleUpdate(BaseRole):
    id: IdType


class RoleOut(SQLBaseModel, BaseRole):
    model_config = ConfigDict(from_attributes=True)

    menu_ids: list[IdType] | None = Field(
        default=None, description="角色具有的所有菜单ID"
    )
    menu_auth_keys: list[str] | None = Field(
        default=None, description="角色具有的所有菜单权限键"
    )

    @model_validator(mode="before")  # 在模型验证前处理数据
    @classmethod
    def extract_fields(cls, data: Any) -> Any:
        return ModelConverter.extract_multiple_in_model_list_fields(
            data,
            [
                ModelConverter.ExtractFieldParam("menus", "id", "menu_ids"),
                ModelConverter.ExtractFieldParam("menus", "auth_key", "menu_auth_keys"),
            ],
        )

class RoleExport(SQLBaseModel, BaseRole):
    model_config = ConfigDict(from_attributes=True)


class RoleAssignPermission(BaseModel):
    id: IdType
    menu_ids: list[IdType] | None = Field(description="菜单ID列表")
